import { checkHttpStatus, parseJSON } from '../utils';
import {  USER_LOGIN_SUCCESS, USER_LOGIN_FAILURE,LOGIN_USER_REQUEST,GET_USERPHONE_USERNAME} from '../contants/index';


export function loginUserSuccess(session) {
    localStorage.clear();
    if(session) {
        localStorage.setItem('session', session);
        localStorage.setItem('isAuthenticated',true);
    }
    return {
        type: USER_LOGIN_SUCCESS,
        payload: {
            session: session,
        }
    }
}

export function loginUserFailure(error) {
  return {
    type: USER_LOGIN_FAILURE,
    payload: {
      errContent: error.content?error.content:error,
      errCode: error.code
    }
  }
}

export function loginUserRequest() {
  return {
    type: LOGIN_USER_REQUEST
  }
}

 export function loginUser(userPhone,userPass) {
     return function(dispatch) {
         dispatch(loginUserRequest());
         return fetch("http://fengke.net:8081/web/login", {
             method: 'POST',
             headers: {
                 'Accept': 'application/json',
                 'Content-Type': 'application/json'
         },
             body: JSON.stringify({
                 userPhone: userPhone,
                 userPass: userPass
         })
 })
    .then(checkHttpStatus)
    .then(parseJSON)
   .then(
         response => {
                 if(response.status=="1"){
                   dispatch(loginUserSuccess(response.data.userId));
                   
                 }else{
                  dispatch(loginUserFailure(response.errmsg));
                 }
     },
         error =>{
                 console.log('login fails:'+error);
     })

   }
 }
